﻿using System.Text.RegularExpressions;
using Convert = iLib.Utils.Convert;

namespace Cms.Web.Framework.Plugins.Helpers
{
    public class SearchResultHelper
    {
        public static string ExtractFirstOccurenceOfSearchQueryFromHtmlWithPadding(string html, string searchQuery)
        {
            html = RemoveHtmlTagsAndNonBreakableSpaces(html);
            html = RemoveTextBeforeFirstMatchPosition(html, searchQuery);
            html = RemoveTextAfterFirstMatchPosition(html, searchQuery);
            return Regex.Replace(html, "(" + Regex.Escape(searchQuery) + ")", "<strong>" + "$1" + "</strong>", RegexOptions.IgnoreCase);
        }

        private static string RemoveHtmlTagsAndNonBreakableSpaces(string html)
        {
            html = Convert.ClearHtmlTags(html, Convert.ClearHtmlAction.StripTags);
            html = html.Replace("&nbsp;", " ").Trim();
            html = html.Replace("\r", " ");
            html = html.Replace("\n", " ");
            while (html.IndexOf("  ") > 0)
            {
                html = html.Replace("  ", " ");
            }
            return html;
        }

        private static string RemoveTextBeforeFirstMatchPosition(string html, string searchQuery)
        {
            int firstMatchPosition = html.ToLower().IndexOf(searchQuery.ToLower());
            if (firstMatchPosition > 100)
            {
                for (int i = firstMatchPosition - 100; i > 0; i--)
                {
                    if (html[i].ToString() == ".")
                    {
                        return html.Substring(i).TrimStart(".".ToCharArray()).TrimStart();
                    }
                }
                for (int i = firstMatchPosition - 100; i > 0; i--)
                {
                    if (html[i].ToString() == " ")
                    {
                        html = html.Substring(i).Trim();
                        return char.IsUpper(html[0]) ? html : "&#133; " + html;
                    }
                }
            }
            return html;
        }

        private static string RemoveTextAfterFirstMatchPosition(string html, string searchQuery)
        {
            if (html.Length - searchQuery.Length > 200)
            {
                for (int i = 200 + searchQuery.Length; i < html.Length; i++)
                {
                    if (html[i].ToString() == "." && i < html.Length - 1)
                    {
                        return html.Remove(i + 1);
                    }
                }
                for (int i = 200 + searchQuery.Length; i < html.Length; i++)
                {
                    if (html[i].ToString() == " " && i < html.Length - 1)
                    {
                        return html.Remove(i + 1) + " &#133;";
                    }
                }
            }
            return html;
        }
    }
}
